package com.chensi.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.chensi.model.User;
import com.chensi.service.IUserService;

public class MyShiroRealm extends AuthorizingRealm
{
	private static final Logger log=Logger.getLogger(MyShiroRealm.class);
	
	@Autowired
	private IUserService userService;
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
	{
		String userId=(String)principals.getPrimaryPrincipal();
		log.info("开始授权,用户id="+userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> urls=new HashSet<String>();
		Set<String> roles=new HashSet<String>();
		roles.add("user");
		urls.add("user:getUser");
		//授权限
		info.addStringPermissions(urls);
		//授角色
		info.addRoles(roles);
		return info;
	}
 
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException
	{
		UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
		User entity=new User();
		entity.setName(token.getUsername());
		User user = userService.getByEntity(entity);
		if(user!=null){
			log.info("开始登录认证,用户名="+user.getName());
			Subject subject=SecurityUtils.getSubject();
			subject.getSession().setAttribute("username", user.getName());
			return new SimpleAuthenticationInfo(token.getUsername(), new String(token.getPassword()), getName());
		}
		return null;
	}
	
}
